package git.soulbgm.utils;

import ch.qos.logback.core.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-07-17 15:29
 * @description IO操作类
 */
@Slf4j
public class IoUtil {

    /**
     * 将文件读出装入byte数组中
     *
     * @param path
     * @return
     */
    public static byte[] toByteArray(String path) {
        FileInputStream is = null;
        try {
            File file = new File(path);
            if (file != null && file.exists()) {
                is = new FileInputStream(file);
                return IOUtils.toByteArray(is);
            }
            return null;
        } catch (IOException e) {
            log.error("读取" + path + "文件成byte数组失败", e);
            return null;
        } finally {
            close(is, null);
        }
    }

    /**
     * 获得文件中的内容
     * @param file
     * @return
     */
    public static String getFileContent(File file) {
        FileInputStream is = null;
        try {
            if (file != null && file.exists()) {
                is = new FileInputStream(file);
                return byteArrayToString(IOUtils.toByteArray(is));
            }
        } catch (IOException e) {
            log.error("读取文件内容失败", e);
            return null;
        }
        return null;
    }

    public static String byteArrayToString(byte[] bytes) {
        String str = null;
        try {
            str = new String(bytes, Charset.forName("UTF-8"));
        } catch (Exception e) {
            return null;
        }
        return str;
    }

    /**
     * 关闭输入流和输出流
     *
     * @param is
     * @param os
     */
    public synchronized static void close(InputStream is, OutputStream os) {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            log.info("关闭读写流失败", e);
        }
    }

}
